package com.sanyang.pda.ui.calendar;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.CalendarView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sanyang.pda.adapter.CalendarAdapter;
import com.sanyang.pda.adapter.PopSelectAdapter;
import com.sanyang.pda.bean.CalendarBean;
import com.sanyang.pda.bean.SelectBean;
import com.sanyang.pda.event.EventDate;
import com.sanyang.pda.net.NetUtils;
import com.sanyang.pda.utils.StringConfig;
import com.sanyang.pda.view.datepicker.CustomDatePicker;
import com.sanyang.pda.view.datepicker.DateFormatUtils;
import com.wangshen.base.app.AppActivityKey;
import com.wangshen.base.net.bean.BaseAppEntity;
import com.wangshen.base.ui.mvp.base.ui.BaseActivity;
import com.wangshen.projectbase.R;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

@Route(path = AppActivityKey.CALENDARACTIVITY)
public class CalendarActivity extends BaseActivity {
    @BindView(R.id.cameraView)
    CalendarView cameraView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.title)
    FrameLayout title;
    PopSelectAdapter adapter;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.rv_calendar)
    RecyclerView rvCalendar;
    CalendarAdapter calendarAdapter;
    private List<CalendarBean> calendarBeans=new ArrayList<>();
    private String entryNo,articleId;
    private int type,index;
    @Override
    public int getView() {
        return R.layout.activity_calendar;
    }

    @Override
    public void initView() {
        adapter = new PopSelectAdapter(R.layout.item_pop_select_list, new ArrayList<>());
        rvList.setLayoutManager(new LinearLayoutManager(this));
        rvList.setAdapter(adapter);
        GridLayoutManager gridLayoutManager=new GridLayoutManager(mContext,7);
        rvCalendar.setLayoutManager(gridLayoutManager);
        calendarAdapter=new CalendarAdapter(R.layout.item_calendar,calendarBeans);
        rvCalendar.setAdapter(calendarAdapter);
    }

    @Override
    public void initLinsenterner() {
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter1, @NonNull View view, int position) {
                EventDate eventDate=new EventDate(type,index,adapter.getData().get(position).getName());
                EventBus.getDefault().post(eventDate);
                finish();
            }
        });
        calendarAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                EventDate eventDate=new EventDate(type,index,getDate(calendarAdapter.getData().get(position)));
                EventBus.getDefault().post(eventDate);
                finish();
            }
        });
    }
    private String getDate(CalendarBean calendarBean){
        String month="";
        String day="";
        if (calendarBean.getDay() < 10){
            day="0"+calendarBean.getDay();
        }else {
            day=String.valueOf(calendarBean.getDay());
        }
        if (calendarBean.getMonth() < 10){
            month="0"+calendarBean.getMonth();
        }else {
            month=String.valueOf(calendarBean.getMonth());
        }
        return calendarBean.getYear()+"-"+month+"-"+day;
    }
    @Override
    public void getData() {
        entryNo=getIntent().getExtras().getString(StringConfig.ENTRYNO);
        articleId=getIntent().getExtras().getString(StringConfig.ID);
        type=getIntent().getExtras().getInt(StringConfig.TYPE);
        index=getIntent().getExtras().getInt(StringConfig.INDEX);
        Calendar cd = Calendar.getInstance();
        calendarBeans=getNowMonthDays(cd.get(Calendar.YEAR),cd.get(Calendar.MONTH)+1);
        tvTitle.setText(cd.get(Calendar.YEAR)+"年"+(cd.get(Calendar.MONTH)+1)+"月");
        initDatePicker();
        NetUtils.geApi().palletShelves(entryNo, articleId, type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseAppEntity<List<String>>>() {
                    @Override
                    public void accept(BaseAppEntity<List<String>> manualPickingBeanBaseAppEntity) throws Exception {
                        List<SelectBean> selectBeans = new ArrayList<>();
                        for (String item : manualPickingBeanBaseAppEntity.getData()) {
                            selectBeans.add(new SelectBean(item, ""));
                        }
                        adapter.setNewInstance(selectBeans);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }
    /**
     * 获取当前月天数
     *
     * @param year  年
     * @param month 月
     * @return
     */
    public List<CalendarBean> getNowMonthDays(int year, int month) {
        List<CalendarBean> list=new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        //月第一天周几
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 1){
            list.add(new CalendarBean(0));
        }
        if (week == 2){
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
        }
        if (week == 3){
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
        }
        if (week == 4){
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
        }
        if (week == 5){
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
        }
        if (week == 6){
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
            list.add(new CalendarBean(0));
        }
        //月天数
        int maximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        //int[] days = new int[maximum];
        for (int i = 0; i < maximum; i++) {
            Calendar cb = Calendar.getInstance();
            CalendarBean calendarBean=new CalendarBean(i+1,month,year,1);
            if (year == cb.get(Calendar.YEAR) && month == (cb.get(Calendar.MONTH)+1) && (i+1) > cb.get(Calendar.DATE)){
                calendarBean.setSelect(false);
            }
            list.add(calendarBean);
        }
        return list;
    }
    private CustomDatePicker mDatePicker;

    private void initDatePicker() {
        long beginTimestamp = DateFormatUtils.str2Long("2000-01-01", false);
        long endTimestamp = DateFormatUtils.str2Long("2500-01-01", false);
        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(mContext, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp, TextView v) {
                v.setText(Integer.parseInt(getYearDateTime(timestamp))+"年"+Integer.parseInt(getFormatedDateTime(timestamp))+"月");
                calendarAdapter.setNewInstance(getNowMonthDays(Integer.parseInt(getYearDateTime(timestamp)),Integer.parseInt(getFormatedDateTime(timestamp))));
                cameraView.setDate(timestamp);
            }
        }, beginTimestamp, endTimestamp);
    }

    @OnClick({R.id.iv_back, R.id.tv_title})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_title:
                mDatePicker.show(System.currentTimeMillis(), tvTitle);
                break;
        }
    }
    /**
     * 将long转换为日期（yyyy-MM-dd HH:mm）
     * @param dateTime
     * @return 到分
     */
    @SuppressLint("SimpleDateFormat")
    public static String getYearDateTime(long dateTime) {
        String time="";
        try {
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy");
            time=sDateFormat.format(new Date(dateTime + 0));
        }catch (Exception e){

        }
        return time;
    }
    /**
     * 将long转换为日期（yyyy-MM-dd HH:mm）
     * @param dateTime
     * @return 到分
     */
    @SuppressLint("SimpleDateFormat")
    public static String getFormatedDateTime(long dateTime) {
        String time="";
        try {
            SimpleDateFormat sDateFormat = new SimpleDateFormat("MM");
            time=sDateFormat.format(new Date(dateTime + 0));
        }catch (Exception e){

        }
        return time;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
